package com.bmw.regist.service.impl;

import com.bmw.regist.common.base.BaseResponse;
import com.bmw.regist.common.base.Constant;
import com.bmw.regist.common.exception.ErrorMessage;
import com.bmw.regist.dao.RegisterDao;
import com.bmw.regist.model.Register;
import com.bmw.regist.model.http.UserReq;
import com.bmw.regist.service.RegistService;
import com.bmw.regist.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.Date;
@Service
@Slf4j
public class RegistServiceImpl implements RegistService {
    @Autowired
    private RegisterDao registerDao;

    @Autowired
    RedisUtil redisUtil;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse regist(UserReq req) throws Exception{
        log.info("===[开始调用秒杀接口(乐观锁)]===");
        log.info("===[校验用户手机号]===");
        BaseResponse paramValidRes = validateParam(req.getPhone());
        if (paramValidRes.getCode()!=0){
            return paramValidRes;
        }
        log.info("效验通过");
        return createOptimisticOrder(req.getPhone(),req.getSms());
    }

    private BaseResponse createOptimisticOrder(String phone,String sms) throws Exception{
        log.info("开始注册逻辑");
        Date date = new Date();
        Register register = new Register();
        register.setPhone(phone);
        register.setSms(sms);
        register.setCreateTime(date);
        registerDao.insert(register);
        log.info("===[注册成功]===");

        //判断重复的逻辑
        if (hasOrderedUserCache(phone)){
            log.error("===[用户重复注册！]===");
            return BaseResponse.error(ErrorMessage.REPEAT_ORDER_ERROR);
        }
        try {
            addOrderedUserCache(phone);
        } catch (Exception e) {
            log.error("===[记录已购用户缓存时发生异常！]===", e);
        }
        return BaseResponse.OK;
    }

    public Boolean hasOrderedUserCache(String phone) {
        String key = String.format(Constant.redisKey.SECKILL_ORDERED_USER, phone);
        return redisUtil.sHasKey(key,phone);
    }
    public void addOrderedUserCache(String phone) {
        String key = String.format(Constant.redisKey.SECKILL_ORDERED_USER, phone);
        redisUtil.sSet(key, phone);
        log.info("===[已将已购用户放入缓存！]===");
    }
    private BaseResponse validateParam(String phone) {
        if (hasOrderedUserCache(phone)) {
            log.error("===[用户重复注册！]===");
            return BaseResponse.error(ErrorMessage.REPEAT_ORDER_ERROR);
        }
        return BaseResponse.OK;
    }
}

